﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNet.Random.ResourceService
{
    public class StatisticsAddressExtension
    {
        #region statistics address

        public static string AddressListToJson()
        {
            var data = ProcessAddressList();
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return json;
        }

        #region private method

        private static List<AddressModel> ProcessAddressList()
        {
            var address = new StatisticsAddress();
            var list = address.GetAddressList20111031();

            var clong = address.GetAddressList20111031();

            foreach (var item in list)
            {
                if (!IsProvince(item.num))
                {
                    var province = FindProvince(clong, item.num);
                    if (IsCity(item.num))
                    {
                        var temp = province + item.address;
                        item.address = temp;
                    }
                    else
                    {
                        var city = FindCity(clong, item.num);
                        var temp = province + city + item.address;
                        item.address = temp;
                    }
                }
                System.Diagnostics.Debug.WriteLine("id : " + item.id + " num :" + item.num + " address " + item.address);
            }
            return list;
        }

        private static bool IsCity(string num)
        {
            var res = false;
            var three = num.Substring(3, 3);
            if (!three.StartsWith("0") && three.EndsWith("00"))
            {
                res = true;
            }
            return res;
        }

        private static bool IsProvince(string num)
        {
            var res = false;
            var three = num.Substring(3, 3);
            if (three == "000")
            {
                res = true;
            }
            return res;
        }

        private static string FindCity(List<AddressModel> list, string num)
        {
            var res = "";
            var four = num.Substring(0, 4) + "00";
            var data = list.Where(d => d.num == four).FirstOrDefault();
            if (data != null)
            {
                res = data.address;
            }
            return res;
        }

        private static string FindProvince(List<AddressModel> list, string num)
        {
            var res = "";
            num = num.Substring(0, 3) + "000";
            var data = list.Where(d => d.num == num).FirstOrDefault();
            if (data != null)
            {
                res = data.address;
            }
            return res;
        }

        #endregion

        #endregion
    }
}
